package com.heiye.blog.ai.strategy.text.impl;

import com.heiye.blog.ai.enums.TextModelTypeEnum;
import com.heiye.blog.ai.helper.AdvisorHelper;
import com.heiye.blog.ai.model.dto.AIChatRequest;
import com.heiye.blog.ai.model.openrouter.OpenRouterApi;
import com.heiye.blog.ai.model.openrouter.OpenRouterAssistantMessage;
import com.heiye.blog.ai.model.openrouter.OpenRouterChatModel;
import com.heiye.blog.ai.model.openrouter.OpenRouterChatOptions;
import com.heiye.blog.ai.model.vo.AIResponse;
import com.heiye.blog.ai.model.vo.AiChatReqVO;
import com.heiye.blog.ai.strategy.text.TextModelStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author: heiye
 * @date: 2025/11/11 下午6:13
 * @version: v1.0.0
 * @description: OpenRouter 的谷歌 Gemini-2.5-pro 模型策略实现类
 */
@Slf4j
@Component
public class GoogleGeminiV2_5ProStrategy implements TextModelStrategy {

    @Resource
    private WebClient.Builder webClientBuilder;

    @Resource
    private AdvisorHelper advisorHelper;

    @Value("${spring.ai.openrouter.api-key}")
    private String apiKey;

    /**
     * 获取存储类型枚举
     *
     * @return TextModelTypeEnum
     */
    @Override
    public TextModelTypeEnum getTextModelType() {
        return TextModelTypeEnum.GOOGLE_GEMINI_2_5_PRO;
    }

    /**
     * 处理流式响应
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public Flux<AIResponse> handleStreamResponse(AIChatRequest aiChatRequest) {
        // 对参数进行审查，对于一些必须填写的字段进行填写
        reviewAndOptimizeRequest(aiChatRequest);

        // 用户消息
        String userMessage = aiChatRequest.getUserMessage();

        // 构建 ChatModel
        ChatModel chatModel = OpenRouterChatModel.builder()
                .openRouterApi(OpenRouterApi.builder()
                        .apiKey(apiKey)
                        // 使用自定义 webClientBuilder
                        .webClientBuilder(webClientBuilder)
                        .build())
                .build();

        // 创建 ChatClient
        ChatClient.ChatClientRequestSpec chatClientRequestSpec = ChatClient.create(chatModel)
                .prompt()
                // 构建配置
                .options(OpenRouterChatOptions.builder()
                        .model(getTextModelType().getType())
                        .thankMaxTokens(aiChatRequest.getThinkMaxTokens())
                        .exclude(aiChatRequest.getExclude())
                        .temperature(aiChatRequest.getTemperature())
                        .build())
                .user(userMessage);

        // 添加 Advisor
        List<Advisor> advisors = advisorHelper.buildAdvisors(aiChatRequest);
        chatClientRequestSpec.advisors(advisors);

        // 使用原子布尔值跟踪分隔线状态（每个请求独立）
        AtomicBoolean needSeparator = new AtomicBoolean(true);

        return chatClientRequestSpec.stream()
                .chatResponse()
                .mapNotNull(response -> {
                    // 转化类型 OpenRouterAssistantMessage
                    OpenRouterAssistantMessage assistantMessage = (OpenRouterAssistantMessage) response.getResult().getOutput();

                    // 获取推理内容
                    String reasoningContent = assistantMessage.getReasoningContent();

                    // 获取文本
                    String text = assistantMessage.getText();

                    // 是否是正式回答
                    boolean isTextResponse = false;

                    // 若推理内容有值，则响应推理内容，否则，说明推理结束了，响应正式回答
                    String processed;
                    if (StringUtils.isNotEmpty(reasoningContent)) {
                        processed = reasoningContent;
                    } else {
                        processed = text;
                        // 标记为正式回答
                        isTextResponse = true;
                    }

                    // 在正式回答内容之前，添加一个回车
                    if (isTextResponse
                            && needSeparator.compareAndSet(true, false)) {
                        processed = "\n" + processed;
                    }

                    return AIResponse.builder()
                            .v(processed)
                            .build();
                });
    }

    /**
     * 对参数进行审查
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public void reviewAndOptimizeRequest(AIChatRequest aiChatRequest) {
        // https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking?hl=zh-cn#budget
        // 默认开启深度思考
        aiChatRequest.setThinkEnable(true);
        // 对于 gemini-2.5-pro 模型，让他自己使用 API 时控制思考预算
        aiChatRequest.setThinkMaxTokens(-1);
//        // 获取模型温度
//        Double temperature = aiChatRequest.getTemperature();
//
//        // 如果没设置温度则设置默认温度
//        if (Objects.isNull( temperature)) {
//            // 设置默认温度
//            aiChatRequest.setTemperature(0.7);
//        }
    }
}
